local class = require 'hump.class'

local cache = {}

local function cacheGraphics(filename)
  if filename then
    if not cache[filename] then
      cache[filename] = love.graphics.newImage(filename)
    end
    return cache[filename]
  end
end

Drawable = class{
  function(self, cx, cy, width, height, filename)
    self:move(cx, cy)
    self.filename = filename
    self.graphics = cacheGraphics(filename)
    self:setSize(width, height)
    self:rotate(0)
  end
}

function Drawable:move(cx, cy)
  if not cx then error('cx cannot equal nil') end
  self.cx = cx
  if not cy then error('cy cannot equal nil') end
  self.cy = cy
end

function Drawable:rotate(radians)
  self.rotation = radians
end

function Drawable:setSize(width, height)
  self.width = width
  self.height = height
  if self.graphics then
    self.scalex = width/self.graphics:getWidth()
    self.scaley = height/self.graphics:getHeight()
  end
end

function Drawable:draw()
  draw(self.cx, self.cy, self.width, self.height, self.rotation, self.filename)
end

function Drawable.draw(cx, cy, width, height, rotation, filename, aspect)
  local graphics = cacheGraphics(filename)
  
  love.graphics.translate(cx, cy)
  love.graphics.rotate(rotation)
  if graphics then
    if aspect then
      local aheight = graphics:getHeight()*width/graphics:getWidth()
      if aheight >= height then
        height = aheight
      end
      local awidth = graphics:getWidth()*height/graphics:getHeight()
      if awidth >= width then
        width = awidth
      end
    end
    scalex = width/graphics:getWidth()
    scaley = height/graphics:getHeight()
    love.graphics.draw(graphics, -width/2, -height/2, 0, scalex, scaley)
  else
    love.graphics.rectangle('fill', -width/2, -height/2, width, height)
  end
  love.graphics.rotate(-rotation)
  love.graphics.translate(-cx, -cy)
end
